package cn.com.project;

import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
@DubboService(version = "1.0.0", protocol = "dubbo")
@RefreshScope
public class ApiServiceImpl implements ApiService {

    /**
     * Nacos Config
     */
    @Value("${userConfig.name:Wang}")
    private String name;

    @Value("${userConfig.age:15}")
    private Integer age;

    /**
     * Dubbo
     */
    @Override
    public String sayHello(String name) {
        System.out.println("Provider2 : Hello " + name);
        return "Hello " + name;
    }

    @Override
    public boolean saveUser(User user) {
        System.out.println("Provider2 : " + user);
        return true;
    }

    @Override
    public List<User> listUser() {
        List<User> list = new ArrayList<>();
        list.add(new User(name, age));

        System.out.println("Provider2 : " + list);
        return list;
    }

    /**
     * Seata
     */
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public String account(String userId, int money) {
        // 扣减金额
        int result = jdbcTemplate.update(
                "update account set money = money - ? where user_id = ?",
                new Object[] { money, userId });
        if (result == 1) {
            return "SUCCESS";
        }
        return "FAIL";
    }

    @Override
    public String storage(String goodsCode, int count) {
        // 随机模拟异常
        if (new Random().nextBoolean()) {
            throw new RuntimeException("This is a mock Exception");
        }
        // 扣减库存
        int result = jdbcTemplate.update(
                "update storage set count = count - ? where goods_code = ?",
                new Object[] { count, goodsCode });
        if (result == 1) {
            return "SUCCESS";
        }
        return "FAIL";
    }
}
